#include "server.h"

#include <iostream>
#include <thread>
#include <mutex>
#include <csignal>

#include <boost/asio/io_context.hpp>

bool b_stop = false;
std::condition_variable cond_quit;
std::mutex mtx_quit;

//信号回调函数
void signal_handler(int signum)
{
    if(signum == SIGINT || signum == SIGTERM)
    {
        std::cout << "\tSignal: " << signum << "\n";
        std::unique_lock<std::mutex> lck(mtx_quit);
        b_stop = true;
        cond_quit.notify_one(); //唤醒主线程
    }
}


void exit_by_signal()
{
    try
    {
        boost::asio::io_context ioc;

        std::thread work([&ioc](){
            Server server(ioc, 8080);
            ioc.run();
        });

        //捕获信号
        signal(SIGINT, signal_handler);
        signal(SIGTERM, signal_handler);

        while(!b_stop)
        {
            std::cout << "Waiting for signal..." << std::endl;
            std::unique_lock<std::mutex> lck(mtx_quit);
            cond_quit.wait(lck); //等待信号唤醒
            std::cout << "Signal received, continue..." << std::endl;
        }

        ioc.stop();
        work.join();
    }
    catch (const std::exception& e)
    {
        std::cout << "Exception: " << e.what() << "\n";
        return;
    }
}

void exit_by_boost()
{
    try
    {
        boost::asio::io_context ioc;
        //捕获对应ioc的信号
        boost::asio::signal_set signals(ioc, SIGINT, SIGTERM);
        //异步等待信号
        signals.async_wait([&ioc](boost::system::error_code ec, int signum){
            if(ec)
                return;
            std::cout << "\tSignal: " << signum << "\n";
            ioc.stop();
        });

        Server server(ioc, 8080);
        ioc.run();
    }
    catch (const std::exception& e)
    {
        std::cout << "Exception: " << e.what() << "\n";
        return;
    }
}

int main(void)
{
    // exit_by_signal();
    exit_by_boost();
    
    return 0;
}